<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.id" :placeholder="$t('employeeAttendanceTable.id')" style="width: 150px;" class="filter-item" maxlength="32" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.jobNumber" :placeholder="$t('employeeAttendanceTable.jobNumber')" style="width: 150px;" class="filter-item" maxlength="32" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.employeeName" :placeholder="$t('employeeAttendanceTable.employeeName')" style="width: 150px;" class="filter-item" maxlength="32" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.dept" :placeholder="$t('employeeAttendanceTable.dept')" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in statusOption" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-date-picker v-model.trim="listQuery.startDate" :placeholder="$t('table.startDate')" value-format="yyyy-MM-dd" type="date" style="width: 150px;" class="filter-item" maxlength="32" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model.trim="listQuery.endDate" :placeholder="$t('table.endDate')" value-format="yyyy-MM-dd" type="date" style="width: 150px;" class="filter-item" maxlength="32" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{ $t('table.export') }}</el-button>
      <el-row :gutter="20" type="flex">
        <el-col :span="1" :offset="0">
          <el-upload
            ref="upload"
            class="upload-demo"
            action="doUpload"
            :limit="1"
            :before-upload="beforeUpload"
          >
            <el-button slot="trigger" v-waves :loading="downloadLoading" size="middle" type="primary" class="filter-item" icon="el-icon-upload">{{ $t('table.eximport') }}</el-button>
          </el-upload>
        </el-col>
        <el-col :span="1" :offset="1">
          <el-button v-waves :loading="downloadLoading" size="middle" type="primary" class="filter-item" icon="el-icon-download" @click="exportDownload">{{ $t('table.export') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="$t('employeeAttendanceTable.id')" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.jobNumber')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.jobNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.employeeName')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.employeeName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.dept')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.dept }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.standardWorkHour')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.standardWorkHour }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.actualWorkHour')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.actualWorkHour }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.lateNumber')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.lateNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.lateMinute')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.lateMinute }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.leaveEarlyNumber')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.leaveEarlyNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.leaveEarlyMinute')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.leaveEarlyMinute }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.overtimeHour')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.overtimeHour }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.holidayOvertimeHour')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.holidayOvertimeHour }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.attendanceDay')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.attendanceDay }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.businessTripDay')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.businessTripDay }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.absenteeismDay')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.absenteeismDay }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.askForLeaveDay')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.askForLeaveDay }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.standardAdditionalWage')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.standardAdditionalWage }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.overtimeAdditionalWage')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.overtimeAdditionalWage }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.allowanceAdditionalWage')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.allowanceAdditionalWage }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.lateDeductionWage')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.lateDeductionWage }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.askForLeaveDeductionWage')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.askForLeaveDeductionWage }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.deductDeductionWage')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deductDeductionWage }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.realWage')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.realWage }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.remarks')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.remarks }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.remarks')" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.remarks }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.imgUrl')" width="" align="center">
        <template slot-scope="scope">
          <el-popover placement="bottom" trigger="click"> <!--trigger属性值：hover、click、focus 和 manual-->
            <a :href="scope.row.imgUrl" target="_blank" title="查看最大化图片">
              <img :src="scope.row.imgUrl" style="width: 160px;height: 160px">
            </a>
            <img slot="reference" :src="scope.row.imgUrl" style="width: 50px;height: 50px; cursor:pointer" />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column :label="$t('employeeAttendanceTable.createTime')" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" align="center" width="310" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button plain type="primary" size="mini" style="width:68px;" @click="handleUploadImg(scope.row)">{{ $t('userTable.uploadImg') }}</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />
    <el-dialog :visible.sync="dialogResourceVisible" title="配置资源">
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogResourceVisible = false">{{ $t('table.cancel') }}</el-button>
        <!-- <el-button type="primary" @click="updateRoleResource">{{ $t('table.confirm') }}</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, uploadEmployee, uploadImg, exportList } from '@/api/employee/employee.attendance'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'EmployeeAttendanceTable',
  components: { Pagination },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'info',
        0: 'danger'
      }
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusNameMap = {
        1: '启用',
        0: '禁用'
      }
      return statusNameMap[status]
    }
  },
  data() {
    return {
      filterText: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 20,
        id: '',
        jobNumber: null,
        employeeName: '',
        dept: ''
      },
      statusOption: [{ label: '启用', key: '1' }, { label: '禁用', key: '0' }],
      dialogFormVisible: false,
      dialogResourceVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      roleForm: {
        id: '',
        roleName: '',
        roleKey: '',
        roleLevel: '',
        roleStatus: 1,
        description: ''
      },
      rules: {

      },
      downloadLoading: false,
      oldResourceList: [],
      defaultProps: {
        children: 'children',
        label: 'resourceName'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs['tree'].filter(val)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.resourceName.indexOf(value) !== -1
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.count
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    resetroleForm() {
      this.roleForm = {
        id: '',
        roleName: '',
        roleKey: '',
        roleLevel: '',
        roleStatus: 1,
        description: ''
      }
    },
    handleCreate() {
      this.resetroleForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['roleForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.roleForm = Object.assign({}, row) // copy obj
      this.roleForm.roleStatus = parseInt(this.roleForm.roleStatus)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['roleForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm(
        '此操作将永久删除该角色：' + row.roleName + ', 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.listLoading = true
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    setCheckedKeys(keys) {
      if (this.$refs['tree']) {
        this.$refs['tree'].setCheckedKeys(keys)
      }
    },
    resetChecked() {
      if (this.$refs['tree']) {
        this.$refs['tree'].setCheckedKeys([])
      }
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '序号',
          '角色名称',
          '角色标识',
          '角色级别',
          '创建时间',
          '角色状态'
        ]
        const filterVal = [
          'id',
          'roleName',
          'roleKey',
          'roleLevel',
          'createTime',
          'roleStatus'
        ]
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '角色列表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'createTime') {
            return parseTime(v[j])
          } else if (j === 'roleStatus') {
            return this.$options.filters['statusNameFilter'](v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    beforeUpload(file) {
      this.files = file
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!extension && !extension2) {
        this.$message.warning('上传模板只能是 xls、xlsx格式!')
        return
      }
      if (!isLt5M) {
        this.$message.warning('上传模板大小不能超过 5MB!')
        return
      }
      this.fileName = file.name
      setTimeout(() => {
        this.submitUpload()
      }, 500)
      return false // 返回false不会自动上传
    },
    submitUpload() {
      console.log('上传' + this.files.name)
      if (this.fileName === '') {
        this.$message.warning('请选择要上传的文件！')
        return false
      }
      this.downloadLoading = true
      const fileFormData = new FormData()
      fileFormData.append('file', this.files, this.fileName)
      uploadEmployee(fileFormData).then(res => {
        this.downloadLoading = false
      })
    },
    handleUploadImg(row) {
      const input = document.createElement('input')
      input.setAttribute('type', 'file')
      input.click()
      input.onchange = () => {
        const file = input.files[0]
        if (/^image\//.test(file.type)) {
          const fileFormData = new FormData()
          fileFormData.append('file', file)
          fileFormData.append('id', row.id)
          uploadImg(fileFormData).then(res => {
            if (res.code === 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        } else {
          console.warn('You could only upload images')
        }
      }
    },
    async exportDownload() {
      await exportList().then(res => {
      })
    }
  }
}
</script>
